import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/models/common_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/event.dart';
import 'package:geomancy/tools/http.dart';
import 'package:geomancy/tools/upload.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_loading_circle.dart';
import 'package:geomancy/widgets/gallery_util/components/clip_center.dart';
import 'package:go_router/go_router.dart';
import 'package:image_editor/image_editor.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';

class CropAvatarPage extends StatefulWidget {
  final AssetEntity entity;
  const CropAvatarPage({super.key, required this.entity});

  @override
  State<CropAvatarPage> createState() => _CropAvatarPageState();
}

class _CropAvatarPageState extends State<CropAvatarPage> {
  final GlobalKey<ExtendedImageEditorState> avatarEditorKey =GlobalKey<ExtendedImageEditorState>();
  File? photoFile;

  @override
  void initState() {
    super.initState();
    getFile();
  }

  Future getFile() async {
    File? tmpFile = await widget.entity.file;
    setState(() {
      photoFile = tmpFile;
    });
  }

  //裁剪图片
  Future cropHandle() async {
    final Rect? cropRect = avatarEditorKey.currentState?.getCropRect();
    final Uint8List? img = avatarEditorKey.currentState?.rawImageData;
    final EditActionDetails? action = avatarEditorKey.currentState?.editAction;
    final int? rotateAngle = action?.rotateAngle.toInt();
    final bool? flipHorizontal = action?.flipY;
    final bool? flipVertical = action?.flipX;
    ImageEditorOption option = ImageEditorOption();
    if (action!.needCrop) {
      option.addOption(ClipOption.fromRect(cropRect!));
    }
    if (action.needFlip) {
      option.addOption(FlipOption(horizontal: flipHorizontal!, vertical: flipVertical!));
    }
    if (action.hasRotateAngle) {
      option.addOption(RotateOption(rotateAngle!));
    }
    Uint8List? tmp = img;
    for (final group in option.groupList) {
      if (group.canIgnore) {
        continue;
      }
      final handler = ImageHandler.memory(tmp);
      final editOption = ImageEditorOption();
      for (final option in group) {
        editOption.addOption(option);
      }
      editOption.outputFormat = option.outputFormat;
      tmp = await handler.handleAndGetUint8List(editOption);
    }
    Directory tempDir = await getTemporaryDirectory();
    final name = DateTime.now().millisecondsSinceEpoch;
    File file = File('${tempDir.path}/$name.jpg');
    if (tmp != null) {
      await file.writeAsBytes(tmp);
      final fileSize = await file.length();//字节
      if (!Utils.isPictureInMaxSize(fileSize)) {
        if (mounted) context.pop();
        return;
      }
    }
    //获取全局存储的裁剪标记，看是在注册步骤还是修改个人头像步骤
    if (mounted) {
      // final scene = context.read<GalleryProvider>().getGalleryScene;
      // context.read<GalleryProvider>().setCropFile = file;
      eventListener.emit(Constant.CROPAVATAR, file);
      context.pop();
      context.pop();
      // if (scene == GalleryScene.registerAvatar) {
      //
      // } else if (scene == GalleryScene.avatar) {
      //   editUserAvatar(file);
      // }
    }
  }

  Future editUserAvatar(File file) async {
    try {
      EasyLoading.show(status: '头像上传中...');
      final QiNiuResponseModel? res = await QiNiu.uploadImage(context, file: file, type: UploadBucketType.userAvatar);
      if (res != null && mounted) {
        final isSafe = await QiNiu.censorImage(context, res.url);
        if (!isSafe) {
          EasyLoading.dismiss();
          EasyLoading.showInfo('头像涉嫌违规！请重新上传');
          return;
        }
      }
      if (!mounted) return;
      final User? user = context.read<UserProvider>().getUserInfo;
      final data = await Fetch.request(Method.POST, '/romko/user/modifyUserInfo', params: {
        'avatar': res?.url,
        'nickName': user?.username
      }, context: context);
      final result = CommonModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        if (mounted) {
          user!.setAvatar = res?.url;
          context.read<UserProvider>().saveUserInfo(user);
          context.pop();
          context.pop();
        }
      }
    } catch(e) {
      rethrow;
    } finally {
      EasyLoading.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            color: Colors.black,
          ),
          photoFile != null ? Align(
              child: ExtendedImage.file(
                photoFile!,
                fit: BoxFit.contain,
                mode: ExtendedImageMode.editor,
                extendedImageEditorKey: avatarEditorKey,
                cacheRawData: true,
                initEditorConfigHandler: (state) {
                  return EditorConfig(
                    maxScale: 2.0,
                    cropAspectRatio: 1,
                    cropRectPadding: EdgeInsets.zero,
                    initCropRectType: InitCropRectType.layoutRect,
                    hitTestSize: 20.0,
                    lineColor: Colors.transparent,
                    lineHeight: 1.w,
                    cornerSize: const Size(0, 0),
                    cornerColor: Colors.transparent,
                    editorMaskColorHandler: (BuildContext context, bool pointerDown) {
                      return const Color.fromRGBO(0, 0, 0, 0);
                    },
                  );
                },
              )
          ) : Align(
              child: CommonLoadingCircleWidget(lineWidth: 3.w)
          ),
          ClipCenter(
              boundWidth: 750.w,
              borderRadius: 375.w
          ),
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: SafeArea(
              top: false,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 40.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      onTap: () {
                        context.pop();
                      },
                      child: Container(
                        width: 64.w,
                        height: 64.w,
                        color: Colors.transparent,
                        alignment: Alignment.center,
                        child: Text('取消', style: TextStyle(fontSize: 30.sp, color: Colors.white)),
                      ),
                    ),
                    GestureDetector(
                      onTap: cropHandle,
                      child: Container(
                        width: 120.w,
                        height: 56.w,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: ColorStyle.red,
                            borderRadius: BorderRadius.all(Radius.circular(28.w))
                        ),
                        child: Text('确定', style: TextStyle(fontSize: 30.sp, color: Colors.white)),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
